//package com.xiguaji.tiktok.task.market.event;
//
//import com.google.common.eventbus.AllowConcurrentEvents;
//import com.google.common.eventbus.Subscribe;
//import com.xiguaji.boot.eventbus.Event;
//import com.xiguaji.boot.eventbus.EventBusTemplate;
//import com.xiguaji.boot.eventbus.IEventListener;
//import com.xiguaji.boot.toolkit.JsonUtil;
//import com.xiguaji.tiktok.task.common.job.TaskParam;
//import com.xiguaji.tiktok.task.core.ScheduleTemplate;
//import com.xiguaji.tiktok.task.market.model.author.Author;
//import com.xiguaji.tiktok.task.market.model.BloggerMarket;
//import com.xiguaji.tiktok.task.market.model.author.MarketAuthorResponse;
//import com.xiguaji.tiktok.task.market.model.Pagination;
//import com.xiguaji.tiktok.task.market.model.distribution.Property;
//import com.xiguaji.tiktok.task.market.repository.BloggerMarketRepository;
//import com.xiguaji.tiktok.task.market.spider.MarketSpiderClient;
//import com.xxl.job.core.log.XxlJobLogger;
//import lombok.SneakyThrows;
//import lombok.val;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.util.concurrent.ThreadPoolExecutor;
//import java.util.concurrent.TimeUnit;
//
//@Component
//public class FetchBloggerMarketEventListener implements IEventListener<FetchBloggerMarketEventListener.FetchBloggerMarketEvent> {
//
//    @Autowired
//    MarketSpiderClient marketSpiderClient;
//
//    @Autowired
//    BloggerMarketRepository bloggerMarketRepository;
//
//    @Autowired
//    @Lazy
//    EventBusTemplate eventBusTemplate;
//
//    @Autowired
//    ScheduleTemplate scheduleTemplate;
//    /**
//     * 临时写死，重构后走配置
//     */
//    private int queueSize=30000;
//    private int corePollSize=400;
//    private int maxPollSize=400;
//    private ThreadPoolExecutor customPoolMain;
//    final String updateBloggerMain = "UpdateBloggerMain-worker";
//    @PostConstruct
//    public void init() {
//        customPoolMain = scheduleTemplate.getCustomThreadPool(updateBloggerMain, corePollSize, corePollSize, 0, queueSize, TimeUnit.MINUTES);
//
//    }
//    @SneakyThrows
//    @Override
//    @Subscribe
//    @AllowConcurrentEvents
//    public void handle(FetchBloggerMarketEvent event) {
//        int page = 1;
//        val fetchBloggerMarketDistributionEvent = new FetchBloggerMarketDistributionEventListener.FetchBloggerMarketDistributionEvent(event,6715265791018663941L);
//        eventBusTemplate.post(fetchBloggerMarketDistributionEvent);
//
//        MarketAuthorResponse marketAuthorResponse =  marketSpiderClient.getAuthors(page,30);
//        Pagination pagination = marketAuthorResponse.getData().getPagination();
//        int totalPage = pagination.getTotal_count()%pagination.getLimit() == 0?
//                pagination.getTotal_count()/pagination.getLimit():
//                pagination.getTotal_count()/pagination.getLimit()+1;
//
//        while (page <= totalPage){
//            /*marketAuthorResponse.getData().getAuthors().forEach( author -> {
//                run(author,event);
//            });*/
//
//            for (Author author : marketAuthorResponse.getData().getAuthors()) {
//                run(author,"FetchBloggerMarketEventListener");
//            }
//
//
//            page++;
//            if(page > totalPage){
//                if(event.loop){
//                    page = 1;
//                }
//            }
//            marketAuthorResponse =  marketSpiderClient.getAuthors(page,30);
//            Thread.sleep(1000*60);
//        }
//
//    }
//    @SneakyThrows
//    public int handle(int page, String who, TaskParam taskParam ) {
//        long start=System.currentTimeMillis();
//        MarketAuthorResponse marketAuthorResponse =  marketSpiderClient.getAuthors(page,taskParam.getRecords());
//        if(marketAuthorResponse.getCode()==30181){
//            XxlJobLogger.log("页数过头:code={},msg={},耗时={}",marketAuthorResponse.getCode(),marketAuthorResponse.getMsg(),(System.currentTimeMillis() - start) / 1000);
//            return marketAuthorResponse.getCode();
//        }
//        if(marketAuthorResponse.getCode()!=0){
//            XxlJobLogger.log("异常结束:code={},msg={},耗时={}",marketAuthorResponse.getCode(),marketAuthorResponse.getMsg(),(System.currentTimeMillis() - start) / 1000);
//            return marketAuthorResponse.getCode();
//        }
//        Pagination pagination = marketAuthorResponse.getData().getPagination();
//        customPoolMain.submit(() ->marketAuthorResponse.getData().getAuthors().parallelStream().forEach(author->{
//            long startTmp=System.currentTimeMillis();
//            try {
//                run(author,who);
//                XxlJobLogger.log("更新结束:uid={},耗时={}",author.getCore_user_id(),(System.currentTimeMillis() - start) / 1000);
//
//            }catch (Exception e){
//                XxlJobLogger.log("异常结束:uid={},msg={},耗时={}",author.getCore_user_id(),e.getMessage(),(System.currentTimeMillis() - startTmp) / 1000);
//
//            }
//        })).get();
//
//        XxlJobLogger.log("更新结束:page={},LimitSize={},totalCount={},耗时={}",pagination.getPage(),pagination.getLimit(),pagination.getTotal_count(),(System.currentTimeMillis() - start) / 1000);
//        return marketAuthorResponse.getCode();
//    }
//    public void run(Author author,String eventSource){
//        long start=System.currentTimeMillis();
//        BloggerMarket bloggerMarket = bloggerMarketRepository.findByMarketId(author.getId());
//
//        if(null == bloggerMarket){
//            //bloggerMarket.setId(1);
//            bloggerMarket = new BloggerMarket();
//            bloggerMarket.setCoreUserId(author.getCore_user_id());
//            bloggerMarket.setMarketId(author.getId());
//            bloggerMarket.setCreateBy(eventSource);
//            bloggerMarket.setUpdateBy(eventSource);
//            bloggerMarket.setAgeDistribution("");
//            bloggerMarket.setGenderDistribution("");
//            bloggerMarket.setRegionDistribution("");
//            bloggerMarket.setRegionGeonameidDistribution("");
//            bloggerMarket.setStateDistribution("");
//            bloggerMarket.setStateGeonameidDistribution("");
//        }
//        bloggerMarket.setECart(author.getE_cart() != 0);
//        bloggerMarket.setAgeMaxRatio(author.getAudience_profile().getAge().getMax_ratio());
//        bloggerMarket.setAgeMaxDistribution(author.getAudience_profile().getAge().getMax_distribution());
//        bloggerMarket.setGenderMaxRatio(author.getAudience_profile().getGender().getMax_ratio());
//        bloggerMarket.setGenderMaxDistribution(author.getAudience_profile().getGender().getMax_distribution());
//        bloggerMarket.setRegionMaxRatio(author.getAudience_profile().getRegion().getMax_ratio());
//        bloggerMarket.setRegionMaxDistribution(author.getAudience_profile().getRegion().getMax_distribution());
//
//        val distribution = marketSpiderClient.getDistribution(bloggerMarket.getMarketId());
//        for (Property property : distribution.getData().getActive()) {
//            if(property.getProperty().equals("active")){
//                bloggerMarket.setActive(property.getValue());
//            }else if(property.getProperty().equals("inactive")){
//                bloggerMarket.setInactive(property.getValue());
//            }
//        }
//        bloggerMarket.setAgeDistribution(JsonUtil.parseJson(distribution.getData().getAge()));
//        bloggerMarket.setGenderDistribution(JsonUtil.parseJson(distribution.getData().getGender()));
//        bloggerMarket.setRegionDistribution(JsonUtil.parseJson(distribution.getData().getRegion()));
//        bloggerMarket.setRegionGeonameidDistribution(JsonUtil.parseJson(distribution.getData().getRegion_geonameid()));
//        bloggerMarket.setStateDistribution(JsonUtil.parseJson(distribution.getData().getState()));
//        bloggerMarket.setStateGeonameidDistribution(JsonUtil.parseJson(distribution.getData().getState_geonameid()));
//        bloggerMarket.setUpdateBy(eventSource);
//        bloggerMarketRepository.save(bloggerMarket);
//        XxlJobLogger.log("用户更新成功:uid={},耗时={}", author.getCore_user_id(),(System.currentTimeMillis() - start) / 1000);
//
//    }
//
//    public static class FetchBloggerMarketEvent extends Event{
//
//        private boolean loop;
//
//        public FetchBloggerMarketEvent(boolean loop) {
//            super("FetchBloggerMarket");
//            this.loop = loop;
//        }
//    }
//}
